package joodle.domain;

import static java.lang.Math.*;

import java.awt.geom.Path2D;

/**
 * One of the basic shapes included in joodle out of box. It is a subclass of 
 * AbstractShape and inherits most of its methods. The draw, hasEnoughPoints, isPointOn 
 * and asXML methods will be overridden in these basic shapes classes to give the proper 
 * functionality to each of the basic shapes.
 */

public class Ellipse extends AbstractShape {
	
	public Ellipse() {
		super();
	}
	
	protected Ellipse(Ellipse e) {
		super(e);
	}
	
	/**
	 * Checks if there are enough points to create an Ellipse object
	 * @return a boolean value depends on the enough points condition
	 * @see Shape#hasEnoughPoints()
	 */
	@Override
	public boolean hasEnoughPoints() {
		return points.size() > 1;
	}
	
	/**
	 * Updates the last point of the Ellipse shape
	 * @see AbstractShape#updateEndPoint(Point)
	 * @param Point p
	 */
	@Override
	public void updateEndPoint(Point p) {
		if(!hasEnoughPoints())
			return;
		points.set(1, p);
		remakeAwtShape();
	}
	
	/**
	 * Creates a clone of the Ellipse shape
	 * @return a new Ellipse shape
	 * @see Shape#cloneShape()
	 */
	@Override
	public Shape cloneShape() {
		return new Ellipse(this);
	}
	/**
	 * Creates a character sequence which is the XML representation of the Ellipse
	 * @return string includes XML representation of the Ellipse
	 * @see Shape#asXML()
	 */
	@Override
	public String asXML() {
		StringBuilder sb = new StringBuilder();

		Point p1 = points.get(0);
		Point p2 = points.get(1);
		double cx = (p1.getX() + p2.getX()) / 2.0f; 
		double cy = (p1.getY() + p2.getY()) / 2.0f;
		double rx = (max(p1.getX(), p2.getX()) - min(p1.getX(), p2.getX())) / 2.0f;
		double ry = (max(p1.getY(), p2.getY()) - min(p1.getY(), p2.getY())) / 2.0f;
		
		sb.append(String.format("<ellipse cx=\"%f\" cy=\"%f\" rx=\"%f\" ry=\"%f\"",
				cx, cy, rx, ry));
		
		sb.append(attributesAsXML());
		sb.append(transformAsXML());
		
		sb.append(" />\n");

		return sb.toString();
	}
	/**
	 * Returns Ellipse to it's original format
	 * @return an AWT version of the Ellipse
	 * @see AbstractShape#remakeAWTShape()
	 */
	@Override
	protected void remakeAwtShape() {
		Point p1 = points.get(0);
		Point p2 = points.get(1);
		float xMin = Math.min(p1.getX(), p2.getX());
		float yMin = Math.min(p1.getY(), p2.getY());
		float xMax = Math.max(p1.getX(), p2.getX());
		float yMax = Math.max(p1.getY(), p2.getY());
		path = new Path2D.Float(
				new java.awt.geom.Ellipse2D.Float(xMin, yMin, xMax - xMin, yMax - yMin));		
	}

}
